package listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import static view.EditorFrame.*;
import view.PictureModel;

import model.DataModel;
import model.DataReadWrite;

public class SaveListener implements ActionListener{
	private JFrame frame;
	private PictureModel pictureModel;
	private JTextPane textPane;
	public SaveListener(JFrame frame,PictureModel pictureModel, JTextPane textPane){
		this.frame = frame;
		this.pictureModel = pictureModel;
		this.textPane = textPane;
	}
	@Override
	public void actionPerformed(ActionEvent event) {
		JFileChooser fc = new JFileChooser();
		fc.setFileFilter(new FileNameExtensionFilter("fcd", "FCD"));
		fc.setCurrentDirectory(new File("/"));
		int retVal = fc.showSaveDialog(frame);
		if (retVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			datamodel = new DataModel(pictureModel);
			datamodel.getWrapper();
			if(datamodel.getBlocks().size() == 0){
				textPane.setText("There are not any block to save");
				return;
			}
			textPane.setText("Save OK...");
			try {
				DataReadWrite.writeFlowchart(file, datamodel);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(frame, "Invalid save operation",
						"Error", JOptionPane.ERROR_MESSAGE);
			}
		}
		
	}

}
